import jwt
from django.http import JsonResponse
from django.conf import settings

from apps.users.models import User


class LoginValidMixin(object):
    def dispatch(self,request,*args,**kwargs):
        #接收请求报文头中的身份信息
        token = request.META.get('HTTP_AUTHORIZATION')
        if len(token)<=4:
            return JsonResponse({"msg":'缺少身份信息'},status=401)
        token = token[4:]

        #解码验证
        try:
            payload = jwt.decode(token,settings.SECRET_KEY)
        except:
            return JsonResponse({'msg':"身份信息无效"},status=401)

        #获取用户编号
        user_id = payload.get('id')
        #查询当前登录的对象
        user= User.objects.get(pk= user_id)
        #在后续的视图可以访问当前的用户
        request.user = user
        return super().dispatch(request,*args,**kwargs)